package com.sxbbc.api.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sxbbc.common.basics.utils.statics.EnumUtils;
import com.sxbbc.common.core.entity.jz.*;
import com.sxbbc.common.core.enums.*;
import com.sxbbc.common.core.mapper.jz.*;
import com.sxbbc.common.core.service.*;
import com.sxbbc.common.core.service.system.mode.ModeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.function.common.GetRest;
import com.function.common.RestResponse;
import com.sxbbc.api.service.ICustomerService;
import com.sxbbc.common.basics.emails.SendMail;
import com.sxbbc.common.basics.enums.LoginChannelEnums;
import com.sxbbc.common.basics.enums.ServiceEnums;
import com.sxbbc.common.basics.exceptions.ThrowJsonException;
import com.sxbbc.common.basics.login.LoginDto;
import com.sxbbc.common.basics.sms.SendSms;
import com.sxbbc.common.basics.utils.calculation.CalcuUtils;
import com.sxbbc.common.basics.utils.encrypts.pwd.Encode;
import com.sxbbc.common.basics.utils.regular.RpxUtils;
import com.sxbbc.common.basics.utils.statics.StaticUtils;
import com.sxbbc.common.core.dto.jz.CustomerTeamVo;
import com.sxbbc.common.core.dto.jz.CustomerVo;
import com.sxbbc.common.core.service.system.login.LoginTokenService;
import com.sxbbc.common.core.service.system.pay.PayService;
import com.sxbbc.common.core.utils.BasePage;
import com.sxbbc.common.core.utils.MsgUtils;

@Service
public class CustomerServiceImpl implements ICustomerService {

    @Autowired
    private ChickenCouponMapper chickenCouponMapper;
    @Autowired
    private CMoneyDetailMapper cMoneyDetailMapper;
    @Autowired
    private BankDetailMapper bankDetailMapper;
    @Autowired
    private AgAgentMapper agAgentMapper;
    @Autowired
    private ICCollectProService collectProService;
    @Autowired
    private ICCustomerService customerService;
    @Autowired
    private ISysCashDetailsService sysCashDetailsService;
    @Autowired
    private BBusinessService bBusinessService;
    @Autowired
    private IInfoParamService infoParamService;
    @Autowired
    private IAccountChangeService accountChangeService;
    @Autowired
    private ICustomerLevelInfoService customerLevelInfoService;
    @Autowired
    private ICCustomerAuthenService customerAuthenService;
    @Autowired
    private ICPayLogService icPayLogService;
    @Autowired
    private ICCollectBusService collectBusService;
    @Autowired
    private PayService payService;
    @Autowired
    private LoginTokenService loginTokenService;
    @Autowired
    private ICPushLogService icPushLogService;
    @Autowired
    private CCustomerMapper customerMapper;
    @Autowired
    private BAccountMapper bAccountMapper;
    @Autowired
    private CAccountMapper cAccountMapper;
    @Autowired
    private ModeService modeService;

    /**
     * 发送修改密码验证码
     *
     * @param phone 手机号
     * @return
     */
    public RestResponse sendUpdatePwdCode(String phone) {
        if (StringUtils.isBlank(phone)) {
            return GetRest.getFail("手机号不能为空");
        }
        // 校验用户信息
        CCustomer cCustomer = new CCustomer();
        cCustomer.setPhone(phone);
        CCustomer customer = customerService.getCustomer(cCustomer);
        if (customer == null) {
            return GetRest.getFail("用户信息有误");
        }
        // 发送验证码到手机号
        return SendSms.getInstance().sendSmsAliyun(phone, MsgUtils.ALI_SMS_RESET_PASSWORD);
    }

    /**
     * 修改用户登录密码
     *
     * @param cid
     * @param phone     手机号
     * @param validcode 验证码
     * @param passWord  密码
     * @return
     */
    public RestResponse handleCustomerPassword(Integer cid, String phone, String validcode, String passWord) {
        String result = RpxUtils.getInstance().validPassword(passWord);
        if (!result.equals("")) {
            return GetRest.getFail(result);
        }
        // 校验验证码
        RestResponse restResponse = SendSms.getInstance().validSms(phone, validcode);
        if (!restResponse.isStatus()) {
            return restResponse;
        }
        String pwd = Encode.md5Encode(passWord);
        return customerService.updateCustomerPassword(cid, pwd);
    }

    /**
     * 修改用户支付密码
     *
     * @return
     */
    public RestResponse handleCustomerPayword(Integer cid, String phone, String validcode, String payWord, Integer type) {
        CalcuUtils calc = CalcuUtils.getInstance();
        String result = RpxUtils.getInstance().validPayWord(payWord);
        if (!result.equals("")) {
            return GetRest.getFail(result);
        }
        //TODO 上线需取消注释
        // 校验验证码
//		RestResponse restResponse = SendSms.getInstance().validSms(phone, validcode);
//		if (!restResponse.isStatus()) {
//			return restResponse;
//		}
        String pwd = Encode.md5Encode(payWord);
        //XXX 默认修改用户密码不安全  万恶的APP和前端要我改的
        if (type == null) {
            type = 1;
        }
        if (calc.isEquals(type, PasswordTypeEnums.CUSTOMER_PAY.getId())) {
            return customerService.updateCustomerPayword(cid, pwd);
        } else if (calc.isEquals(type, PasswordTypeEnums.BUSINESS_PAY.getId())) {
            BBusiness business = new BBusiness();
            business.setCid(cid);
            QueryWrapper<BBusiness> queryWrapper = new QueryWrapper<BBusiness>(business);
            business = bBusinessService.getOne(queryWrapper);
            if (business == null) {
                return GetRest.getFail("商家信息获取失败，请检查网络");
            }
            business.setPayWord(pwd);
            boolean b = bBusinessService.updateById(business);
            if (b) {
                return GetRest.getSuccess("保存成功");
            } else {
                return GetRest.getFail("保存失败");
            }
        } else {
            return GetRest.getFail("不支持的业务类型");
        }
    }

    /**
     * 发送绑定验证码
     *
     * @param bindStr 绑定的账号 （根据type）
     * @param type    1手机号 2邮箱
     * @return
     */
    public RestResponse sendBindCode(String bindStr, Integer type) {
        if (type == null) {
            return GetRest.getFail("请选择绑定类型");
        }

        CCustomer customer = new CCustomer();
        RestResponse restResponse = null;

        // 绑定手机号
        if (CalcuUtils.getInstance().isEquals(type, StaticUtils.PHONE_LOGIN)) {
            // 验证手机号
            String phoneResult = RpxUtils.getInstance().validPhone(bindStr);
            if (!phoneResult.equals("")) {
                return GetRest.getFail(phoneResult);
            }
            // 校验用户信息
            customer.setPhone(bindStr);
            customer = customerService.getCustomer(customer);
            if (customer != null) {
                return GetRest.getFail("该手机号已绑定");
            }
            // 发送验证码到手机号
            restResponse = SendSms.getInstance().sendSmsAliyun(bindStr, MsgUtils.ALI_SMS_BIND_PHONE);
            // 绑定邮箱
        } else if (CalcuUtils.getInstance().isEquals(type, StaticUtils.EMAIL_LOGIN)) {
            // 验证邮箱
            boolean emailResult = RpxUtils.getInstance().validEmail(bindStr);
            if (!emailResult) {
                return GetRest.getFail("邮箱格式有误");
            }
            // 校验用户信息
            customer.setEmail(bindStr);
            customer = customerService.getCustomer(customer);
            if (customer != null) {
                return GetRest.getFail("该邮箱已绑定");
            }
            // 发送验证码到邮箱
            restResponse = SendMail.getInstance().sendValid(bindStr);
        }
        // 发送验证码
        return restResponse;
    }

    /**
     * 设置用户邮箱
     *
     * @param cid
     * @param email
     * @return
     */
    public RestResponse updateCustomerEmail(Integer cid, String email, String validcode) {
        CCustomer cCustomer = new CCustomer();
        cCustomer.setEmail(email);
        CCustomer customer = customerService.getCustomer(cCustomer);
        if (customer != null) {
            return GetRest.getFail("该邮箱已绑定");
        }
        RestResponse restResponse = SendMail.getInstance().validEmail(email, validcode);
        if (!restResponse.isStatus()) {
            return restResponse;
        }
        return customerService.updateCustomerEmail(cid, email);
    }

    /**
     * 设置手机号
     *
     * @param cid
     * @param phone
     * @param validcode
     * @return
     */
    public RestResponse updateCustomerPhone(Integer cid, String phone, String validcode) {
        CCustomer cCustomer = new CCustomer();
        cCustomer.setPhone(phone);
        CCustomer customer = customerService.getCustomer(cCustomer);
        if (customer != null) {
            return GetRest.getFail("该手机号已绑定");
        }
        RestResponse restResponse = SendSms.getInstance().validSms(phone, validcode);
        if (!restResponse.isStatus()) {
            return restResponse;
        }
        return customerService.updateCustomerPhone(cid, phone);
    }

    /**
     * 修改手机号
     *
     * @param cid
     * @param oldphone
     * @param newphone
     * @param validcode
     * @return
     */
    @Override
    public RestResponse updateNewCustomerPhone(Integer cid, String oldphone, String newphone, String validcode) {
        if (StringUtils.isBlank(oldphone)) {
            return GetRest.getFail("请输入原有手机号");
        }
        if (StringUtils.isBlank(newphone)) {
            return GetRest.getFail("请输入修改后的手机号");
        }
        if (oldphone.equals(newphone)) {
            return GetRest.getFail("两次输入的手机号一致，无需修改!");
        }
        //验证旧的手机号
        CCustomer cCustomer = new CCustomer();
        cCustomer.setPhone(oldphone);
        CCustomer oldCustomer = customerService.getCustomer(cCustomer);
        if (oldCustomer == null) {
            return GetRest.getFail("账号异常");
        }
        if (oldCustomer.getAuthen().equals(StaticUtils.STATUS_NO)) {
            return GetRest.getFail("您未实名认证，无法修改手机号");
        }

        //验证新的手机号
        cCustomer.setPhone(newphone);
        CCustomer customer = customerService.getCustomer(cCustomer);
        if (customer != null) {
            return GetRest.getFail("该手机号已绑定");
        }
        RestResponse restResponse = SendSms.getInstance().validSms(newphone, validcode);
        if (!restResponse.isStatus()) {
            return restResponse;
        }
        //修改手机号
        CCustomer changeCustomer = customerService.getById(cid);
        if (changeCustomer == null) {
            return GetRest.getFail("用户信息有误");
        }
        changeCustomer.setPhone(newphone);
        changeCustomer.setLogin(newphone);
        boolean update = customerService.updateById(changeCustomer);
        if (!update) {
            throw new ThrowJsonException("修改手机号异常");
        }
        return GetRest.getSuccess("修改手机号成功");
    }

    @Override
    public RestResponse editCustomerInfo(Integer cid, String headUrl, String nickName) {
        CCustomer customer = customerService.getById(cid);
        if (customer == null) {
            return GetRest.getFail("保存失败");
        }
        if (!StringUtils.isBlank(headUrl)) {
            customer.setHeadurl(headUrl);
        }
        if (!StringUtils.isBlank(nickName)) {
            customer.setNickName(nickName);
        }
        Boolean result = customerService.updateById(customer);
        if (result) {
            return GetRest.getSuccess("保存成功");
        }
        return GetRest.getFail("保存失败");
    }

    @Override
    public RestResponse handleCustomerCashApply(SysCashDetails cashDetails, String payWord) {
        CCustomer customer = customerService.getById(cashDetails.getTargetId());
        if (customer == null) {
            return GetRest.getFail("获取用户信息失败");
        }
        if (CalcuUtils.getInstance().isEquals(customer.getStatus(), StaticUtils.STATUS_NO)) {
            customerService.checkFrezeeCustomer(UserFreezeEnums.CUSTOMER_CASH.getId(), null);
        }

        if (!CalcuUtils.getInstance().isEquals(customer.getAuthen(), StaticUtils.STATUS_YES)) {
            return GetRest.getFail("请先进行身份认证", null, "2");
        } else {
            //实名认证后需要判断该用户是否绑定银行卡
            QueryWrapper<CCustomerAuthen> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("cid", cashDetails.getTargetId());
            CCustomerAuthen authen = customerAuthenService.getOne(queryWrapper);
            if (authen == null) {
                return GetRest.getFail("请求错误，错误代码0000");
            } else if (StringUtils.isBlank(authen.getBankCard())) {
                //验证银行卡是否绑定
                int count = bankDetailMapper.countBankDetailByTargetId(cashDetails.getTargetId());
                if (count == 0) {
                    return GetRest.getFail("请先绑定银行卡");
                }
            }
        }

        // 校验密码
        if (StringUtils.isEmpty(payWord)) {
            return GetRest.getFail("请输入支付密码");
        }
        String encryPayword = Encode.md5Encode(payWord);
        if (!encryPayword.equals(customer.getPayWord())) {
            if (StringUtils.isBlank(customer.getPayWord())) {
                return GetRest.getFail("您还未设置支付密码", null, "1");
            } else {
                return GetRest.getFail("支付密码不正确");
            }
        }

        RestResponse result = sysCashDetailsService.handleCashApply(cashDetails);
        return result;

    }

    @Override
    public Map<String, Object> queryCustomerAccount(Integer cid) {
        CCustomer customer = customerService.getById(cid);
        if (customer == null) {
            throw new ThrowJsonException("获取用户信息失败");
        }
        CAccount account = cAccountMapper.getByCid(cid);
        if (account == null) {
            throw new ThrowJsonException("用户账户信息查询失败");
        }

        // 交易钱包金额
        BigDecimal money = BigDecimal.ZERO;
        QueryWrapper<BBusiness> wrapper = new QueryWrapper<BBusiness>();
        wrapper.eq("cid", cid);
        BBusiness business = bBusinessService.getOne(wrapper);
        if (business != null) {
            BAccount bAccount = bAccountMapper.getByBid(business.getId());
            if (bAccount != null) {
                money = bAccount.getMoney();
            }
        }

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("money", account.getMoney());
        map.put("point", account.getPoint());
        map.put("donate", account.getDonate());
        map.put("share", account.getShare());
        map.put("payMoney", money);
        map.put("valid", customer.getAuthen());
        return map;

    }

    @Override
    public CustomerVo getMyInfo(String token) {
        CalcuUtils calcuUtils = CalcuUtils.getInstance();
        LoginDto dto = loginTokenService.validLoginLoginDto(token);
        Integer cid = dto.getCid();
        Integer channel = dto.getChannel();
        CCustomer customer = customerService.getById(cid);
        if (customer == null) {
            throw new ThrowJsonException("获取用户信息失败");
        }

        //XXX 新增检查，解决之前unionid为空的用户：微信或者小程序登录用户unionid为空就要求去登录 by Wahyee
//		if(calcuUtils.isEquals(channel, LoginChannelEnums.PROGRAM.getChannel()) || calcuUtils.isEquals(channel, LoginChannelEnums.WX.getChannel())) {
//			if(StringUtils.isBlank(customer.getUnionid())) {
//				throw new ThrowJsonException("997");
//			}
//		}

        CAccount cAccount = cAccountMapper.getByCid(cid);
        if (cAccount == null) {
            throw new ThrowJsonException("获取用户账户信息失败");
        }
        CustomerVo vo = new CustomerVo();
        BeanUtils.copyProperties(customer, vo);
        // 是否设置了支付密码
        if (!StringUtils.isBlank(customer.getPayWord())) {
            vo.setHasPayWord(StaticUtils.STATUS_YES);
        } else {
            vo.setHasPayWord(StaticUtils.STATUS_NO);
        }

        // 推广码
        if (calcuUtils.isEquals(channel, LoginChannelEnums.PROGRAM.getChannel())) {
            vo.setMyQrUrl(customer.getQrProgram());
        } else if (calcuUtils.isEquals(channel, LoginChannelEnums.WX.getChannel())) {
            vo.setMyQrUrl(customer.getQrWx());
        } else {
            vo.setMyQrUrl(customer.getQrApp());
        }
        // 用户等级名称
        CustomerLevelInfo level = customerLevelInfoService.getById(customer.getLevelid());
        if (level != null) {
            vo.setLevelName(level.getName());
        }
        // 处理推荐人等级
        String refereeName = queryRefereeName(customer.getParentid());
        vo.setRefereeName(refereeName);

        // 认证状态
        vo.setAuthenStatus(StaticUtils.STATUS_NO);
        QueryWrapper<CCustomerAuthen> wrapper = new QueryWrapper<CCustomerAuthen>();
        wrapper.eq("cid", cid);
        List<CCustomerAuthen> list = customerAuthenService.list(wrapper);
        if (list != null && list.size() > 0) {
            CCustomerAuthen queryAuthen = list.get(0);
            vo.setAuthenStatus(queryAuthen.getStatus());
        }

        // 账户信息
        vo.setMyPoint(cAccount.getPoint());
        vo.setMyFreezePoint(cAccount.getFreezePoint());
        vo.setMyMoney(cAccount.getMoney());
        vo.setMyFreezeMoney(cAccount.getFreezeMoney());
        // 店铺信息
        vo.setHasBusiness(StaticUtils.STATUS_NO);
        QueryWrapper<BBusiness> queryWrapper = new QueryWrapper<BBusiness>();
        queryWrapper.eq("cid", cid);
        BBusiness business = bBusinessService.getOne(queryWrapper);
        if (business != null && (calcuUtils.isEquals(business.getStatus(), StaticUtils.STATUS_SUCCESS) || calcuUtils.isEquals(business.getOfflineStatus(), StaticUtils.STATUS_SUCCESS))) {
            vo.setBid(business.getId());
            handleBusMsg(vo, business, calcuUtils);
        }
        if (business != null) {
            vo.setBussinessApplyStatus(business.getStatus());
            if (calcuUtils.isEquals(business.getStatus(), StaticUtils.STATUS_INIT)) {
                vo.setBusinessApplyStatusName("未申请");
            } else if (calcuUtils.isEquals(business.getStatus(), StaticUtils.STATUS_APPLY)) {
                vo.setBusinessApplyStatusName("申请中");
            } else if (calcuUtils.isEquals(business.getStatus(), StaticUtils.STATUS_SUCCESS)) {
                vo.setBusinessApplyStatusName("审核通过");
            } else if (calcuUtils.isEquals(business.getStatus(), StaticUtils.STATUS_FAIL)) {
                vo.setBusinessApplyStatusName("审核驳回");
            }
        } else {
            vo.setBid(null);
        }

        //消息未读
        QueryWrapper<CPushLog> msgWrapper = new QueryWrapper<>();
        msgWrapper.eq("cid", cid).eq("reading", StaticUtils.STATUS_NO);
        vo.setMsgNum(icPushLogService.count(msgWrapper));

        //代理信息
        QueryWrapper<AgAgent> agAgentQueryWrapper = new QueryWrapper<>();
        agAgentQueryWrapper.eq("cid", cid);
        AgAgent agAgent = agAgentMapper.selectOne(agAgentQueryWrapper);
        if (agAgent != null && calcuUtils.isEquals(agAgent.getStatus(), StaticUtils.STATUS_SUCCESS)) {
            vo.setAgid(agAgent.getId());
            vo.setAgLevel(EnumUtils.getEnum(AgentLevelEnums.class, EnumUtils.GET_ID, agAgent.getLevel()).getName());
        }
        if (agAgent != null) {
            vo.setAgentApplyStatus(agAgent.getStatus());
            if (calcuUtils.isEquals(agAgent.getStatus(), StaticUtils.STATUS_INIT)) {
                vo.setAgentApplyStatusName("未申请");
            } else if (calcuUtils.isEquals(agAgent.getStatus(), StaticUtils.STATUS_APPLY)) {
                vo.setAgentApplyStatusName("申请中");
            } else if (calcuUtils.isEquals(agAgent.getStatus(), StaticUtils.STATUS_SUCCESS)) {
                vo.setAgentApplyStatusName("审核通过");
            } else if (calcuUtils.isEquals(agAgent.getStatus(), StaticUtils.STATUS_FAIL)) {
                vo.setAgentApplyStatusName("审核驳回");
            }
        }

        //银行卡数量
        QueryWrapper<BankDetail> bankDetailQueryWrapper = new QueryWrapper<>();
        bankDetailQueryWrapper.eq("target_id", cid);
        Integer count = bankDetailMapper.selectCount(bankDetailQueryWrapper);
        vo.setBankNum(count);
        //创业分
        vo.setFraction(cAccount.getPoint());
        //基金
        CMoneyDetail detail = new CMoneyDetail();
        detail.setCid(customer.getId());
        detail.setTypeId(HandleTypeEnums.FUND.getId());
        BigDecimal decimal = cMoneyDetailMapper.queryCustomerSumMoneyByType(detail);
        vo.setFund(decimal);
        //提鸡券数量
        QueryWrapper<ChickenCoupon> couponQueryWrapper = new QueryWrapper<>();
        couponQueryWrapper.eq("cid", customer.getId()).eq("status", ChickenCouponStatusEnums.WAITUSE.getId());
        Integer couponNum = chickenCouponMapper.selectCount(couponQueryWrapper);
        vo.setCouponNum(couponNum);
        //用户收藏的商品数
        QueryWrapper<CCollectPro> collectProQueryWrapper = new QueryWrapper<CCollectPro>();
        collectProQueryWrapper.eq("cid", cid).eq("status", StaticUtils.STATUS_YES);
        Integer collectProduct = collectProService.count(collectProQueryWrapper);
        //用户收藏的店铺数
        QueryWrapper<CCollectBus> busWrapper = new QueryWrapper<CCollectBus>();
        busWrapper.eq("cid", cid).eq("status", StaticUtils.STATUS_YES);
        Integer collectBusiness = collectBusService.count(busWrapper);
        vo.setProNum(collectProduct);
        vo.setBusNum(collectBusiness);
        return vo;
    }

    /**
     * 处理推荐人的名称
     *
     * @param parentId 推荐人id
     * @author xiaoky
     */
    private String queryRefereeName(Integer parentId) {
        String refereeName = "";
        // 推荐人名称
        CCustomer refereeCustomer = customerService.getById(parentId);
        if (refereeCustomer != null) {
            // 默认设置为推荐人的昵称
            refereeName = refereeCustomer.getNickName();
            // 查询推荐人认证信息——取他的真实姓名
            QueryWrapper<CCustomerAuthen> wrapper = new QueryWrapper<CCustomerAuthen>();
            wrapper.eq("cid", refereeCustomer.getId());
            List<CCustomerAuthen> list = customerAuthenService.list(wrapper);
            if (list != null && list.size() > 0) {
                CCustomerAuthen queryAuthen = list.get(0);
                if (CalcuUtils.getInstance().isEquals(queryAuthen.getStatus(), StaticUtils.STATUS_SUCCESS)) {
                    refereeName = queryAuthen.getRealName();
                }
            }
        }
        return refereeName;
    }

    /**
     * 处理店铺信息
     *
     * @param vo         个人中心封装数据
     * @param business   店铺信息
     * @param calcuUtils
     * @author xiaoky
     */
    private void handleBusMsg(CustomerVo vo, BBusiness business, CalcuUtils calcuUtils) {
        // 如果是线上,判断线上状态是否为申请成功状态。 如果是线下,判断线下状态。如果是全部,判断两个状态
        Integer offBusiness = null;
        Boolean hasBusiness = false;
        if (calcuUtils.isEquals(BusinessScopeEnums.ONLINE.getId(), business.getOnOff())) {
            if (calcuUtils.isEquals(StaticUtils.STATUS_SUCCESS, business.getStatus())) {
                hasBusiness = true;
                offBusiness = StaticUtils.STATUS_NO;
            }
        } else if (calcuUtils.isEquals(BusinessScopeEnums.OFFLINE.getId(), business.getOnOff())) {
            if (calcuUtils.isEquals(StaticUtils.STATUS_SUCCESS, business.getOfflineStatus())) {
                hasBusiness = true;
                offBusiness = StaticUtils.STATUS_YES;
            }
        }
        if (hasBusiness) {
            vo.setHasBusiness(StaticUtils.STATUS_YES);
            vo.setOffBusiness(offBusiness);
        }
        //个人商家可以使用付款码
        if (CalcuUtils.getInstance().isEquals(business.getPersonStatus(), StaticUtils.STATUS_YES)) {
            vo.setHasBusiness(StaticUtils.STATUS_YES);
            vo.setOffBusiness(StaticUtils.STATUS_YES);
        }
    }

    @Override
    public IPage<CustomerTeamVo> queryMyTeam(BasePage<CustomerTeamVo> page, CustomerTeamVo team) {
        CCustomer customer = customerMapper.selectById(team.getCid());
        if (customer == null) {
            throw new ThrowJsonException("查询失败");
        }
        if (team.getNowLayer() != null) {
            team.setLevelid(null);
        }

        if (team.getLevelid() != null) {
            team.setLevelid(team.getLevelid() + 1);
            team.setNowLayer(null);
        }
        team.setRecommedLayer(team.getNowLayer());
        team.setNowLayer(customer.getLayer());

        customerMapper.queryMyTeamList(page, team);
        if (page.getRecords() != null) {
            CustomerTeamVo teamVo = new CustomerTeamVo();
            for (CustomerTeamVo record : page.getRecords()) {
                teamVo.setCid(record.getCid());
                int num = customerMapper.countMyTeamNum(teamVo);
                record.setUmbrellaCustomerNum(num);
            }
        }
        return page;
    }

    @Override
    public Map<String, Object> countTeamNum(Integer cid) {
        CCustomer customer = customerMapper.selectById(cid);
        if (customer == null) {
            throw new ThrowJsonException("查询失败");
        }
        CustomerTeamVo team = new CustomerTeamVo();
        team.setCid(cid);
        team.setNowLayer(customer.getLayer());

        // 散户
        team.setLevelid(CustomerLevelEnums.NORMAL.getId());
        int normalNum = customerMapper.countMyTeamNum(team);
        // 养殖户
        team.setLevelid(CustomerLevelEnums.BREEDER.getId());
        int breederNum = customerMapper.countMyTeamNum(team);

        // 小型养殖户 黄金
        team.setLevelid(CustomerLevelEnums.SMALL.getId());
        int smallNum = customerMapper.countMyTeamNum(team);
        // 大型养殖户 钻石
        team.setLevelid(CustomerLevelEnums.LARGE.getId());
        int largeNum = customerMapper.countMyTeamNum(team);

        team.setLevelid(null);
        team.setRecommedLayer(CustomerRelationEnums.DIRECT.getId());
        // 直推
        int direct = customerMapper.countMyTeamNum(team);
        // 间推
        team.setRecommedLayer(CustomerRelationEnums.INDIRECT.getId());
        int indirect = customerMapper.countMyTeamNum(team);

        Map<String, Object> map = new HashMap<>();
        map.put("normalNum", normalNum + breederNum);
        map.put("smallNum", smallNum);
        map.put("largeNum", largeNum);
        map.put("directNum", direct);
        map.put("indirectNum", indirect);
        return map;
    }

    /**
     * 大陆认证需要验证码验证是否本人操作
     *
     * @param phone
     * @return
     */
    @Override
    public RestResponse sendAuthenCode(Integer cid, String phone) {
        if (StringUtils.isBlank(phone)) {
            return GetRest.getFail("手机号不能为空");
        }
        // 校验用户信息
        CCustomer customer = customerService.getById(cid);
        if (customer == null) {
            return GetRest.getFail("用户信息有误");
        }
        // 发送验证码到手机号
        return SendSms.getInstance().sendSmsAliyun(phone, MsgUtils.ALI_SMS_COMMON);
    }

    @Override
    public RestResponse handleCustomerAuthen(CCustomerAuthen authen) {
        if (StringUtils.isBlank(authen.getRealName())) {
            return GetRest.getFail("请输入您的真实姓名");
        }
        if (StringUtils.isBlank(authen.getIdcard())) {
            return GetRest.getFail("请输入证件号码");
        }
        authen.setAuthType(AuthTypeEnums.IDCARD.getId());
        authen.setSex(StaticUtils.SEX_SECRECY);

        // 只有驳回状态才修改信息
        CalcuUtils calcuUtils = CalcuUtils.getInstance();
        Integer authenId = null;
        QueryWrapper<CCustomerAuthen> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cid", authen.getCid());
        List<CCustomerAuthen> list = customerAuthenService.list(queryWrapper);
        if (list != null && list.size() > 0) {
            CCustomerAuthen queryAuthen = list.get(0);
            authenId = queryAuthen.getId();
            if (calcuUtils.isEquals(queryAuthen.getStatus(), StaticUtils.STATUS_APPLY)) {
                return GetRest.getFail("身份认证已提交,请耐心等待审核");
            } else if (calcuUtils.isEquals(queryAuthen.getStatus(), StaticUtils.STATUS_SUCCESS)) {
                return GetRest.getFail("身份认证已通过,无需重复认证");
            } else if (calcuUtils.isEquals(queryAuthen.getStatus(), StaticUtils.STATUS_FAIL)) {
                authen.setStatus(StaticUtils.STATUS_APPLY);
                authen.setCheckTime(null);
            }
        }
//        QueryWrapper<CCustomerAuthen> authenWrapper = new QueryWrapper<>();
//        authenWrapper.eq("idcard", authen.getIdcard()).ne("cid", authen.getCid());
//        int count = customerAuthenService.count(authenWrapper);
//        if (count > 0) {
//            return GetRest.getFail("当前证件已在平台进行过认证");
//        }

        //如果身份证二要素通过那么不需要后台审核
        boolean validResult = CalcuUtils.getInstance().validIdentity2(authen.getRealName(), authen.getIdcard());
        if (validResult) {
            authen.setStatus(StaticUtils.STATUS_SUCCESS);
            authen.setCheckTime(new Date());
        }

        authen.setId(authenId);
        authen.setCreateTime(new Date());
        boolean result = customerAuthenService.saveOrUpdate(authen);
        if (!result) {
            return GetRest.getFail("保存信息失败");
        }

        //身份证验证如果是通过，同步用户认证状态
        if (authen.getAuthType().equals(AuthTypeEnums.IDCARD.getId())) {
            if (calcuUtils.isEquals(authen.getStatus(), StaticUtils.STATUS_SUCCESS)) {
                CCustomer customer = customerService.getById(authen.getCid());
                if (customer == null) {
                    throw new ThrowJsonException("数据有误");
                }
                customer.setAuthen(StaticUtils.STATUS_YES);
                customer.setRealName(authen.getRealName());
                result = customerService.updateById(customer);
                if (!result) {
                    throw new ThrowJsonException("审核失败");
                }
            }
        }
        return GetRest.getSuccess("提交成功");
    }

    @Override
    public RestResponse handleCustomerRecharge(String payWord, CPayLog cPayLog) {
        CCustomer customer = customerService.getById(cPayLog.getCid());
        if (customer == null) {
            return GetRest.getFail("获取用户信息失败");
        }
        // 判断金额
        if (cPayLog.getPayMoney() == null) {
            return GetRest.getFail("请输入充值金额");
        }
        if (BigDecimal.ZERO.compareTo(cPayLog.getPayMoney()) >= 0) {
            return GetRest.getFail("请输入正确的金额");
        }
        if (!PayTypeEnums.isPay(cPayLog.getPayType())) {
            return GetRest.getFail("支付方式不存在");
        }
        if (cPayLog.getPayChannel() == null) {
            return GetRest.getFail("参数错误");
        }
        // 判断密码
//		if (StringUtils.isEmpty(payWord)) {
//			return GetRest.getFail("请输入支付密码");
//		}
//		String encryPayword = Encode.md5Encode(payWord);
//		if (!encryPayword.equals(customer.getPayWord())) {
//			if (StringUtils.isBlank(customer.getPayWord())) {
//				return GetRest.getFail("您还未设置支付密码", null, "1");
//			} else {
//				return GetRest.getFail("支付密码不正确");
//			}
//		}

        String payCode = CalcuUtils.getInstance().getOrderCode("RM");
        // 生成支付记录
        cPayLog.setPayCode(payCode);
        cPayLog.setServiceType(ServiceEnums.RECHARGE_MONEY.getId());
        if (CalcuUtils.getInstance().isEquals(PayChannlEnums.WX_PUBLIC.getId(), cPayLog.getPayChannel())) {
            cPayLog.setOpenId(customer.getOpenidWx());
        } else {
            if (CalcuUtils.getInstance().isEquals(PayChannlEnums.WX_PROGRAM.getId(), cPayLog.getPayChannel())) {
                cPayLog.setOpenId(customer.getOpenidProgram());
            }
        }
        boolean flag = icPayLogService.save(cPayLog);
        if (!flag) {
            throw new ThrowJsonException("生成支付记录失败");
        }

        //支付记录存在之后开始处理订单签名
        return payService.handleSign(cPayLog);
    }

}
